

import Foundation
import UIKit
@objc(ScannerPlugin) class ScannerPlugin:CDVPlugin,QRScanDelegate{
    func cancel() {
        let result = CDVPluginResult(status: .error)
        self.commandDelegate.send(result, callbackId: command.callbackId)
        self.viewController.dismiss(animated: false, completion: nil)
    }
    
    func returnUrl(url: String) {
        let data = ["text":url]
        let result = CDVPluginResult(status: .ok, messageAs: data)
        self.commandDelegate.send(result, callbackId: command.callbackId)
        self.viewController.dismiss(animated: false, completion: nil)
    }
    
    private var command:CDVInvokedUrlCommand!
    @objc func scan(_ command:CDVInvokedUrlCommand!){
        self.command = command
        let QRScan = QRScanViewController()
        QRScan.delegate = self
        QRScan.modalPresentationStyle = .currentContext
        self.viewController.present(QRScan,animated: false,completion: nil)
    }
}
protocol QRScanDelegate:class {
    func returnUrl(url:String)
    func cancel()
}

class QRScanViewController: UIViewController {
    var delegate:QRScanDelegate?

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    override func viewDidLoad() {
        QRScanner.shared.scan { (previewLayer) in
            previewLayer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
            self.view.layer.insertSublayer(previewLayer, at: 0)
            }.completed { (res) in
                self.delegate?.returnUrl(url: res)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let vv = QRScan.init()
        vv.delegate = delegate
        view.addSubview(vv)
        let tapBg = UIPinchGestureRecognizer(target: self, action: #selector(pinchDid(_ :)))
        let doubleClick = UITapGestureRecognizer(target: self, action: #selector(click(_:)))
        doubleClick.numberOfTapsRequired = 2
        self.view.addGestureRecognizer(tapBg)
        self.view.addGestureRecognizer(doubleClick)
    }
    var value:CGFloat!
    var isA:Bool = true
    @objc func pinchDid(_ pinch:UIPinchGestureRecognizer){
        let isE = pinch.velocity > 0
        if(isA != isE){
            isA = isE
            pinch.scale = 1
        }
        let num = QRScanner.shared.factor((value ?? 1) + (pinch.scale - 1)/8)
        value = num
    }
    @objc func click(_:Any){
        _ = QRScanner.shared.factor(1)
        value = 1
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        _ = QRScanner.shared.factor(1, true)
        QRScanner.shared.stopRunning()
    }
}
